package com.golxen.framework.netty;


import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.utils.LogUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class ServerClientProtoBufDecoder extends ByteToMessageDecoder {

    String flag;

    public ServerClientProtoBufDecoder(String flag) {
        this.flag = StringUtils.reverse(flag);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < PBPacket.HDR_SIZE) {
            return;
        }

        ByteBuf byteBuf = in.slice();
        short headerFlag = byteBuf.readShort();
        if (PBPacket.HEADER != headerFlag) {
            byteBuf.readShort();
            return;
        }

        int length = byteBuf.readInt();
        if (length <= 0) {
            LogUtil.COMMON.debug("Message Length Invalid Length = " + length + ", drop this Message.");
            return;
        }

        if (length > in.readableBytes()) {
            return;
        }

        PBPacket pkg = new PBPacket();
        pkg.readHeaderNetty(in);
        int bodyLen = length - PBPacket.HDR_SIZE;
        if (bodyLen > 0) {
            byte[] bytes = new byte[bodyLen];
            in.readBytes(bytes, 0, bodyLen);
            pkg.setBytes(bytes);
        } else {
            pkg.setBytes(new byte[0]);

        }


        out.add(pkg);
    }

}
